package edu.nf.hotel.user.impl;

import edu.nf.hotel.exception.LoginException;
import edu.nf.hotel.user.LoginService;
import edu.nf.hotel.user.User;
import edu.nf.hotel.userdao.UserDao;
import edu.nf.hotel.userdao.impl.UserDaoImpl;
import edu.nf.hotel.util.Md5Util;


/**
 * @Date 2023-06-15
 * @Author 陈
 */
public class LoginServiceImpl implements LoginService {
    /**
     * 会员登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        UserDao userDao = new UserDaoImpl();
        User user = userDao.select(username);
        if (user == null){
            throw new LoginException(500,"此账号没有注册");
        }
//        if (Md5Util.equals(password,user.getPassword())){
//            throw new LoginException(500,"错误的账号或密码");
//        }
        if (!user.getPassword().equals(password)){
            throw new LoginException(500,"错误的账号或密码");
        }
        return user;
    }

    /**
     * 会员注册
     * @param userName
     * @param password
     * @param sex
     * @param phone
     * @param email
     * @param address
     * @return
     */
    @Override
    public User add(String userName, String password, String sex, String phone, String email, String address) {
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setSex(sex);
        user.setPhone(phone);
        user.setEmail(email);
        user.setAddress(address);

        UserDao userDao = new UserDaoImpl();
        User user1 = userDao.select(userName);

        if (user1 == null ){
            //结果集
            userDao.insert(user);
        }else {
            System.out.println(user1);
            throw new LoginException(500,"账号已经注册，请重新输入用户名");
        }
        return user;
    }

    /**
     * 修改会员信息
     * @return
     */
    @Override
    public int update(int id,String userName, String password, String sex, String phone,String email, String address) {
        UserDao dao = new UserDaoImpl();

        User user = new User();
        user.setId(id);
        user.setUserName(userName);
        user.setPassword(password);
        user.setSex(sex);
        user.setPhone(phone);
        user.setEmail(email);
        user.setAddress(address);

        int row = dao.update(user);
        //判断一下
        if(user==null){
            throw new LoginException(500,"数据异常，请重新操作") ;
        }
        if(row<1){
            throw new LoginException(500,"数据异常，请重新操作") ;
        }

        return row;
    }
}
